import { LOGIN_PAGE_URL } from '@/router/router.constant'
import { LoginRequest } from '@/api/system/login.request'
import type { FormInstance, FormRules } from 'element-plus'
import defaultCaptcha from '@/assets/images/default/default-captcha.png'
import { getLoginParams, removeLoginParams, setLoginParams } from '@/utils'

/** 登录页的欢迎语 */
function getLoginWelcome(): string {
  const list = ['许久不见，甚是想念！', '等星星睡了再说想你', '今天营业不休息', '一切就绪，开始你的旅程把！', '未来可期，前行无畏！']
  return list[Math.floor(Math.random() * list.length)]
}

export default () => {
  const route = useRoute()
  const router = useRouter()
  const userStore = useUserStore()

  /** 计算需要跳转的路径 */
  const redirect = (route.query['redirect'] as string) ?? '/'
  /** 验证码图片地址 */
  const captchaURL = ref<string>(defaultCaptcha)
  /** 登录加载状态 */
  const loading = ref<boolean>(false)
  const rememberMe = ref<boolean>(true)
  /** 登录表单数据 */
  const loginForm = ref({} as UserType.LoginParams)
  /** 登录表单校验规则 */
  const loginRules: FormRules<UserType.LoginParams> = {
    username: [{ required: true, message: '账号不可为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不可为空', trigger: 'blur' }],
    captcha: [{ required: true, message: '验证码不可为空', trigger: 'blur' }],
  }

  /** 登录 */
  async function handleLogin(formInstance: FormInstance | undefined) {
    try {
      loading.value = true
      await formInstance?.validate()
      await userStore.login(loginForm.value)
      // 登录成功后执行记住密码的逻辑
      const CACHE_RECORD = buildCacheParams()
      rememberMe.value ? setLoginParams(CACHE_RECORD) : removeLoginParams()
      await router.replace(redirect)
    } catch (error: any) {
      loginForm.value.captcha = ''
      getCaptcha()
      console.log(`登录失败`, error.message || error)
    } finally {
      loading.value = false
    }
  }

  /** 获取登录验证码 */
  async function getCaptcha() {
    try {
      const data = await LoginRequest.getCaptcha()
      captchaURL.value = data.captcha
      loginForm.value.uuid = data.uuid
    } catch (error) {}
  }

  function buildCacheParams() {
    const params = {} as UserType.LoginParamsCache
    params.username = loginForm.value.username
    params.password = loginForm.value.password
    params.rememberMe = rememberMe.value
    return params
  }

  function loadCacheParams() {
    const cache = getLoginParams()
    if (!cache) return
    loginForm.value.username = cache.username
    loginForm.value.password = cache.password
    rememberMe.value = cache.rememberMe
  }

  onMounted(() => {
    if (route.path !== LOGIN_PAGE_URL) return
    getCaptcha() // 初始获取一次验证码
    loadCacheParams() // 读取记住的账号密码
  })

  return { loading, loginForm, loginRules, captchaURL, rememberMe, handleLogin, getCaptcha }
}
